package com.wan.data.resource.converter;

import cn.hutool.core.convert.Converter;
import cn.hutool.core.util.NumberUtil;
import com.wan.util.ObjectUtil;

/**
 * [1,3,15,16] 或 1,3,15,16
 * @author wwh
 * @date 2022/7/5 20:49
 */
public class IntArrayConverter implements Converter<int[]> {
    @Override
    public int[] convert(Object value, int[] defaultValue) throws IllegalArgumentException {
        String string = value.toString();
        if(ObjectUtil.isEmpty(string)){
            return new int[0];
        }
        char first = string.charAt(0);
        if(first == '['){
            string = string.substring(1);
        }
        char last = string.charAt(string.length() - 1);
        if(last == ']'){
            string = string.substring(0,string.length() - 1);
        }
        if (ObjectUtil.isEmpty(string)) {
            return new int[0];
        }
        String[] split = string.split(",");
        int[] ints = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            int parseInt = NumberUtil.parseInt(split[i]);
            ints[i] = parseInt;
        }
        return ints;
    }
}
